<?php


namespace App\Services\SDK;

use App\Models\Order;
use App\Models\TestPay;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;

/**
 * 泊然游戏
 * Class BoRanSDK
 * @package App\Services\SDK
 */
class BoRanSDK extends BaseSDK implements SDK
{
    const SDK_NAME = 'boran';
    const SUCCESS_CODE = 1;
    const SUCCESS_RETURN = 'SUCCESS';
    const FAILURE_RETURN = 'FAILURE';

    public static $loginVerifyUrl
        = [
            'test' => 'http://sdk.user.a.778yx.cn/game/verify/login',
            'prod' => 'http://sdk.user.a.778yx.cn/game/verify/login',
        ];

    public function loginVerify(Request $request)
    {
        if ($token = $request->get('token')) {
            $response = $this->http->post($this->getVerifyLoginUrl(), [
                "form_params" => [
                    'appId' => $this->getAppId(),
                    'token' => $token,
                    'sign'  => $this->makeSign($token)
                ]
            ])->getBody()->getContents();

            $response = json_decode($response, true);

            $result = Arr::get($response, 'status', 0) === self::SUCCESS_CODE;
            $data   = Arr::get($response, 'userId');
            $msg    = Arr::get($response, 'msg', '');

            return [$result, $data, $msg];
        }
        return [false, null, ''];
    }

    public function payCallback(Request $request)
    {
        try {
            $params   = $request->all();
            $extInfo  = Arr::get($params, 'extInfo', '');
            $userId   = Arr::get($params, 'userId', '');
            $orderNum = Arr::get($params, 'orderNum', '');
            $money    = Arr::get($params, 'money', 0);
            $serverId = Arr::get($params, 'serverId', '');
            $roleId   = Arr::get($params, 'roleId', '');
            $roleName = Arr::get($params, 'roleName', '');
            $sign     = Arr::get($params, 'sign', '');
            $status   = Arr::get($params, 'status');

            $str         = "{$this->appId}{$userId}{$orderNum}{$money}{$serverId}{$roleId}{$roleName}{$extInfo}{$status}{$this->getAppKey()}";
            $currentSign = md5($str);

            if ($sign != $currentSign) {
                Log::error("[ORDER PAY CALLBACK SIGN ERROR] app_id: {$this->getAppId()} str: {$str} origin_sign: {$sign} currentSign: {$currentSign}");
                return self::FAILURE_RETURN;
            }

            $fill = [
                'order_no'     => $extInfo,
                'app_id'       => $this->getAppId(),
                'user_id'      => $userId,
                'sdk_order_no' => $orderNum,
                'money'        => $money,
                'server_id'    => $serverId,
                'role_id'      => $roleId,
                'role_name'    => $roleName,
                'request'      => json_encode($params),
            ];

            $order = $this->createOrFirstOrder($fill);
            if ($order && $this->dispatchOrder($order)) {
                return self::SUCCESS_RETURN;
            }

        } catch (\Exception $exception) {
            Log::error("[ORDER PAY CALLBACK DISPATCH ORDER]: " . $exception->__toString());
        }
        return self::FAILURE_RETURN;
    }

    public function makeSign($params)
    {
        return md5("{$this->getAppId()}{$this->getAppKey()}{$params}");
    }

    public function createOrFirstOrder($params)
    {
        if (!$params['sdk_order_no'] || !$params['app_id']) {
            return null;
        }

        return Order::firstOrCreate([
            'app_id'       => $params['app_id'],
            'sdk_order_no' => $params['sdk_order_no'],
        ], $params);
    }

    public function testPay(Request $request)
    {
        $appId    = $request->get('appId');
        $userId   = $request->get('userId');
        $moneyFen = $request->get('moneyFen');
        $serverId = $request->get('serverId');
        $roleId   = $request->get('roleId');
        $sign     = $request->get('sign');

        $str         = "{$appId}{$userId}{$moneyFen}{$serverId}{$roleId}{$this->getAppKey()}";
        $currentSign = md5($str);

        if ($sign != $currentSign) {
            Log::error("[ORDER TEST PAY SIGN ERROR] app_id: {$this->getAppId()} str: {$str} origin_sign: {$sign} currentSign: {$currentSign}");
            return self::FAILURE_RETURN;
        }

        TestPay::create([
           'app_id' => $appId,
           'user_id' => $userId,
           'server_id' => $serverId,
           'role_id' => $roleId,
           'moneyFen' => $moneyFen,
           'sdk_code' => self::SDK_NAME,
        ]);

        // TODO 下发

    }
}
